#!/bin/sh
# 安装Cacti
App=cacti
AppName=Cacti
AppBase=/App/web
AppDir=$AppBase/$App

AppSrcBase=/App/src
cd $AppSrcBase
AppSrcFile=$(find -maxdepth 1 -name "$App-*.tar.*" -type f 2> /dev/null | grep -v "spine" | sed -e 's/^.\///')
AppSrcDir=$(echo $AppSrcFile | sed -e 's/.tar.*$//')

export PATH=/App/mysql/bin:$PATH
database_type=mysql
database_default=cacti
database_hostname=127.0.0.1
database_username=cactiuser
database_password=csACt32i
database_port=3306
database_ssl=false
url_path=/cacti/


finstall() {
    test -d $AppDir && echo "$AppName 已安装" || fupdate
}

fupdate() {
    cd $AppSrcBase
    tar zxf $AppSrcFile || tar jxf $AppSrcFile
    test -d $AppBase || mkdir -p $AppBase
    test -d $AppDir && fbackup && rm -rf $AppDir
    mv $AppSrcDir $AppDir && echo "$AppName 安装成功" || echo "$AppName 安装失败"
}

fbackup() {
    Day=$(date +%Y-%m-%d)
    BackupFile=$App-$Day.tgz
    test -d "$AppDir" && cd $AppBase && tar zcvf $BackupFile $App
}

finit() {
mysql << EOF
    DROP DATABASE IF EXISTS $database_default;
    CREATE DATABASE $database_default;
    GRANT ALL PRIVILEGES ON $database_default.* TO '$database_username'@'%' IDENTIFIED BY '$database_password';
    GRANT PROCESS,SUPER,REPLICATION CLIENT ON *.* TO '$database_username'@'%'IDENTIFIED BY '$database_password';
    FLUSH PRIVILEGES;
EOF

    mysql $database_default < $AppDir/cacti.sql

    cp -vf $AppDir/include/config.php $AppDir/include/config.php.bak

cat > $AppDir/include/config.php << EOF
<?php
    \$database_type = "$database_type";
    \$database_default = "$database_default";
    \$database_hostname = "$database_hostname";
    \$database_username = "$database_username";
    \$database_password = "$database_password";
    \$database_port = "$database_port";
    \$database_ssl = "$database_ssl";
    \$url_path = "$url_path";
?>
EOF

    chown -R php $AppDir
}

ScriptFile=$(basename $0)
case "$1" in
    "install") finstall;;
    "update" ) fupdate;;
    "backup" ) fbackup;;
    "init"   ) finit;;
    * )
    echo "用法：$ScriptFile {install|update|backup|init}"
    ;;
esac
